<?php
	class Etablissement extends Table {
		public $noEtablissement;
		public $nomEtablissement;
		public $villeEtablissement;
		public $typeEtablissement;
		
		public function __construct($nom, $ville, $type) {
			parent::__construct();
			
			$this->noEtablissement = -1;
			
			$this->nomEtablissement = $nom;
			$this->villeEtablissement = $ville;
			
			$this->typeEtablissement = new TypeEtablissement('');
			$this->typeEtablissement->identifiant = $type;
		}
		
		public function ajouter() {
			$st = $this->db->prepare("INSERT INTO Etablissement VALUES(NULL, ?, ?, ?");
			$st->execute(array($this->nomEtablissement,
								$this->villeEtablissement,
								$this->typeEtablissement->identifiant));
								
			$this->noEtablissement = $this->db->lastInsertId();
		}
		
		public function enregistrer() {	
			if ($this->noEtablissement == -1) {
				$this->ajouter();
			}
			else {
				$this->modifier();
			}
		}
		
		public function modifier() {
			$st = $this->db->prepare("UPDATE Etablissement SET nomEtablissement=?, villeEtablissement=?, noTypeEtablissement=? WHERE noEtablissement=?");
			
			$st->execute(array($this->nomEtablissement,
								$this->villeEtablissement,
								$this->typeEtablissement,
								$this->noEtablissement));
		}
		
		public function completer() {
			if (is_numeric($this->noEtablissement) && $this->noEtablissement > 0) {
				$sql = "SELECT * FROM Etablissement WHERE noEtablissement=?";
				
				$st = $this->db->prepare($sql);
				$st->execute(array($this->noEtablissement));
				
				$donnees = $st->fetch(PDO::FETCH_ASSOC);
				
				$this->nomEtablissement = $donnees['nomEtablissement'];
				$this->villeEtablissement = $donnees['villeEtablissement'];
				
				$this->typeEtablissement = new TypeEtablissement('');
				$this->typeEtablissement->identifiant = $donnees['noTypeEtablissement'];
			}
			else {
				// throw new EtablissementInvalideException();
			}
		}
		
		static public function recupererAvecID($id) {
			$etablissement = new Etablissement('', '', -1);
			$etablissement->noEtablissement = $id;
			$etablissement->completer();
			
			return $etablissement;
		}
	}
?>